package org.springframework.samples.jpetstore.web.struts2;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.samples.jpetstore.domain.Cart;
import org.springframework.samples.jpetstore.domain.Item;
import org.springframework.samples.jpetstore.web.struts.CartActionForm;
import org.springframework.samples.jpetstore.web.struts.actions.ActionForm;
import org.springframework.samples.jpetstore.web.struts.actions.ActionForward;
import org.springframework.samples.jpetstore.web.struts.actions.ActionMapping;
import org.springframework.samples.jpetstore.web.struts.actions.HttpServletResponse;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class CartAction extends ActionSupport implements ModelDriven, Preparable, ServletRequestAware {

	private HttpServletRequest request;
	private Cart cart;
	private CartItem cartItem;
	
	
	public void setCartItem(CartItem cartItem) {
		this.cartItem = cartItem;
	}

	public void setServletRequest(HttpServletRequest httpServletRequest) {
		this.request = httpServletRequest;
	}

	public void prepare() throws Exception {
		// TODO Auto-generated method stub
	}

	public Object getModel() {
		return cart;
	}

	public String add() throws Exception {

		String workingItemId = cartForm.getWorkingItemId();
		if (cart.containsItemId(workingItemId)) {
			cart.incrementQuantityByItemId(workingItemId);
		} else {
			// isInStock is a "real-time" property that must be updated
			// every time an item is added to the cart, even if other
			// item details are cached.
			boolean isInStock = getPetStore().isItemInStock(workingItemId);
			Item item = getPetStore().getItem(workingItemId);
			cartForm.getCart().addItem(item, isInStock);
		}

		return SUCCESS;
	}
}
